<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use App\Models\Type;

class TypeController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        //
    	$data = DB::table('types')
    	->where(function($query) use ($request){
    		// 查询数据
    		if(!empty($request->typename)){
    			$request->typename = trim($request->typename);
    			$query->where('name', 'like', '%' . $request->typename . '%');
    		}
    	})
		->orderBy('parent_id','desc')
    	->orderBy('weight', 'desc')
    	->get();
        $type = new Type();
		$data = $type->typeTree($data);
//        dd($data);
    	return view('admin/type/index')->with('data', $data)->with('request', $request);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
		$data = DB::table('types')->orderBy('weight')->get();
        $type = new Type();
        $data = $type->typeTree($data);
		return view('admin/type/create')->with('data', $data);
    }
	
	/**
	 * 获取排序好的栏目分类 01
	 */
	private function getTyleList($data)
	{
		foreach($data as $v){
			if($v->parent_id != 0){
				$tmp = explode(',', $v->path);
				$num = count($tmp) - 1;
				$v->name = str_repeat("|________", $num) . $v->name;
			}
		}
		return $data;
	}

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
		// 表单验证
		$this->validate($request, [
		    'name' => 'required|regex:/.{1,20}/',
		    'parent_id' => 'required',
		],[
		    'name.required' => '栏目名不能为空',
		    'name.regex' => '栏目名长度为1-20位',
		    'parent_id.required' => '父级栏目不能为空',
		]);
		     
		$data = $request->except('_token');
		$model = new Type;
		$model->name = $data['name'];
		$model->is_show = $data['is_show'];
		$model->parent_id = $data['parent_id'];
		$model->weight = empty($data['weight']) ? 0 : $data['weight'];
		$model->keywords = empty($data['keywords']) ? $data['name'] : $data['keywords'];
		$model->description = empty($data['description']) ? $data['name'] : $data['description'];
		$model->img = $data['img'];
		$model->content = empty($data['content']) ? '' : $data['content'];
		
		// 设置栏目路径
		if($data['parent_id'] == 0){
			$model->path = 0;
		} else {
            // 查询出父级栏目的路径 拼接成自己的路径
			$parent_id = $data['parent_id'];
			$path = DB::table('types')->where('id', '=', $parent_id)->value('path');
			$model->path = $path . ',' . $parent_id;
		}
		
		if ($model->save($data)) {
		    return redirect('/admin/type/index');
		} else {
		    return redirect('/admin/type/create');
		}
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        // 修改时要过滤本身栏目ID和自己的子栏目ID
		$typeData = DB::table('types')
            ->where('id', '!=', $id)
            ->where('path', 'not like', '%,'.$id)
            ->where('path', 'not like', '%,'.$id.',%')
            ->orderBy('weight')->get();
        $type = new Type();
        $typeData = $type->typeTree($typeData);
		$olddata = DB::table('types')->find($id);
		return view('admin/type/edit')->with('olddata', $olddata)->with('typeData', $typeData);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
		// 表单验证
		$this->validate($request, [
		    'name' => 'required|regex:/.{1,20}/',
		    'parent_id' => 'required',
		],[
		    'name.required' => '栏目名不能为空',
		    'name.regex' => '栏目名长度为1-20位',
		    'parent_id.required' => '父级栏目不能为空',
		]);
		     
		$data = $request->except(['_token','typeimg']);
		$model = new Type;

		// 设置栏目路径
		if($data['parent_id'] == 0){
            $data['path'] = 0;
		} else {
			$parent_id = $data['parent_id'];
			// 查询出父级栏目的路径 拼接成自己的路径
            $parent_path = DB::table('types')->where('id', '=', $parent_id)->value('path');
            $new_path=$data['path'] = $parent_path . ',' . $parent_id;
            // 查询自己的子类 修改他们的路径. 自己的子类路径一定会比自己的路径长  自己id为5时:  0,2   子类:  0,2,5
			// update users set path=replace(path,$old_path.',',$path.',');
            $old_path = DB::table('types')->where('id', '=', $id)->value('path');
			$new_path .= ",";
			$old_path .= ",";
			DB::update("update blog_types set path=replace(path,\"$old_path\",\"$new_path\")");
		}
		
		if ($model->where('id', '=', $id)->update($data)) {
		    return redirect('/admin/type/index');
		} else {
		    return redirect('/admin/type/create');
		}
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
		DB::table('types')->where('id', '=', $id)->delete();
		return redirect('/admin/type/index');
    }
	
	/**
	 * 批量删除
	 */
	public function dels(Request $request)
	{
		if($ids = $request->input('ids')){
			DB::table('types')->whereIn('id', $ids)->delete();
		}
		return redirect('/admin/type/index');
	}
	
	public function upload(Request $request)
	{
		// 检测是否有文件上传
		if ($request->hasFile('typeimg')) {
			// 微秒时间戳
			$file_name = str_replace(".","",microtime(true)) . mt_rand(1000, 9999);
			// 原始文件后缀
			$type = $request->file('typeimg')->getClientOriginalExtension();
			// 移动文件到目录
			$request->file('typeimg')->move('./upload/type/', 'type_' . $file_name . '_type.' . $type);
			// 返回结果
			$arr = array('state'=>1, 'msg'=>'', 're'=>'/upload/type/type_' . $file_name . '_type.' . $type);
			echo json_encode($arr);
		}
		// dump($request->all());
	}
}
